<template>
  <div class="category">
    <dl class="m-categroy">
      <dt>按拼音首字母选择:</dt>
      <dd v-for="(item, index) in list" :key="index">
        <a :href="'#city-' + item">{{ item }}</a>
      </dd>
    </dl>
    <dl
      class="m-categroy-section"
      v-for="(item, index) in cityGroup"
      :id="'city-' + item.id"
      :key="index"
    >
      <dt>{{ index }}</dt>
      <dd>
        <span @click="changeCity(city)" v-for="city in item" :key="city.id">{{ city.name }}</span>
      </dd>
    </dl>
  </div>
</template>

<script>
import api from '@/api/index';

export default {
  data() {
    return {
      list: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split(''),
      cityList: [],
      cityGroup: [],
    };
  },
  created() {
    api.getCityList().then((res) => {
      const obj = {};
      res.data.data.forEach((item) => {
        if (!obj[item.firstChar.toUpperCase()]) {
          obj[item.firstChar.toUpperCase()] = [];
        }
        obj[item.firstChar.toUpperCase()].push(item);
      });
      this.cityGroup = obj;
    });
  },
  methods: {
    changeCity(city) {
      this.$store.dispatch('setPosition', city);
      this.$router.push({ name: 'index' });
    },
  },
};
</script>

<style lang="scss" scoped>
@import '../../assets/css/changecity/categroy.scss';
</style>
